<template>
	<el-card class="box-card">
		<el-form :model="formData" ref="formData" :rules="rules" label-width="150px">
			<el-form-item class="title" label-width="30px">
				<el-col :span="16">商户添加</el-col>
			</el-form-item>
			<el-form-item label="商户名称" prop="customerName">
				<el-input v-model="formData.customerName" placeholder="请输入商户名称" style="width:65%"></el-input>
				<div style="display: inline-block;color:red;">商户名称必须和营业执照保持一致，修改需要提交申请</div>
			</el-form-item>
			<el-form-item label="联系人姓名" prop="linkerName">
				<el-input v-model="formData.linkerName" placeholder="联系人姓名" style="width:65%;"></el-input>
			</el-form-item>
			<el-form-item label="商户电话" prop="linkerPhone">
				<el-input v-model="formData.linkerPhone" placeholder="商户电话-手机号" style="width:65%;"></el-input>
			</el-form-item>
			<el-form-item label-width="30px" prop="shAddress" style="background-color: #20a0ff;color: #fff;">
				<el-col :span="12">商户地址</el-col>
				<el-col :span="12" style="text-align: right;padding-right: 20px;">
					<span style="margin-right: 10px;">经度</span>
					<el-input size="mini" :readonly="true" v-model="formData.latitude" placeholder="经度" style="width:150px"></el-input>
					<span style="margin: 0 10px;">纬度</span>
					<el-input size="mini" :readonly="true" v-model="formData.longitude" placeholder="纬度" style="width:150px"></el-input>
				</el-col>
			</el-form-item>

			<el-row>
				<el-col :span="8">
					<el-row>
						<el-col :span="20">
							<el-input v-model="etrName" placeholder="输入地址，选择商户位置"></el-input>
						</el-col>
						<el-col :span="4">
							<el-button type="primary" icon="search" @click="find"></el-button>
						</el-col>
					</el-row>
					
					<el-row class="resultMap">
						<el-col :span="24" >
							<div v-for="item in names" class="itemMap" @click="showOver(item)">{{item.address}}</div>
						</el-col>
					</el-row>
				</el-col>
				<el-col :span="16">
					<div id="allmap"></div>
				</el-col>
			</el-row>
			<el-form-item prop="customerAddress" label-width="0" style="margin-top: 10px;">
				<el-input v-model="formData.customerAddress" placeholder="输入商户详细地址"></el-input>
			</el-form-item>
			<el-form-item prop="takePercent" label-width="0" style="margin-top: 10px;">
				<el-input style="width:95%;" type="number" v-model="formData.takePercent" placeholder="商户分成比例，写数字，比如20，写0.2"></el-input>
				<span>%</span>
			</el-form-item>
			<el-form-item label="北京市" prop="shName" label-width="60px">
				<el-select v-model="formData.areaId" placeholder="行政区" @change="changChild">
					<el-option v-for="item in areaList" :key="item.id" :label="item.value" :value="item.id">
					</el-option>
				</el-select>
				<el-select v-model="formData.bizId" placeholder="商圈">
					<el-option v-for="item in bdList" :key="item.id" :label="item.value" :value="item.id">
					</el-option>
				</el-select>
				<el-select v-model="formData.bdId" placeholder="BD负责人">
					<el-option v-for="item in userList" :key="item.userId" :label="item.name" :value="item.userId">
					</el-option>
				</el-select>
				<el-radio class="radio" v-model="formData.runStatus" label="1">营业中</el-radio>
				<el-radio class="radio" v-model="formData.runStatus" label="2">停业中</el-radio>
			</el-form-item>
			<el-form-item class="title" label-width="30px">
				<el-col :span="16">商户营业执照</el-col>
			</el-form-item>
			<ul class="el-upload-list el-upload-list--picture-card" style="float: left;" v-show="hasLicenceImg">
				<li class="el-upload-list__item is-success" v-for="item in licenceImg">
					<img :src="item" alt="" class="el-upload-list__item-thumbnail">
					<i class="el-icon-close"></i>
					<span class="el-upload-list__item-actions" @click="haslicenceImgsRemove(item)">
						<span class="el-upload-list__item-delete"><i class="el-icon-delete2"></i></span>
					</span>
				</li>
			</ul>
			<el-upload class="avatar-uploader" :action="uploadUrl" :before-upload="beforeUpload" list-type="picture-card" :on-success="licenceImgsPreview" :on-remove="licenceImgsRemove">
				<i class="el-icon-plus"></i>
			</el-upload>
			<el-dialog v-model="licenceImgsVisible" size="tiny">
				<img width="100%" :src="licenceImgsUrl" alt="">
			</el-dialog>
			<span>提示:图片不超过1M，上传后显示缩略图</span>
			<el-form-item class="title" label-width="30px">
				<el-col :span="16">商户LOGO</el-col>
			</el-form-item>
			<ul class="el-upload-list el-upload-list--picture-card" style="float: left;" v-show="hasloginImg">
				<li class="el-upload-list__item is-success" v-for="item in loginImg">
					<img :src="item" alt="" class="el-upload-list__item-thumbnail">
					<i class="el-icon-close"></i>
					<span class="el-upload-list__item-actions" @click="haslogoImgsRemove(item)">
						<span class="el-upload-list__item-delete"><i class="el-icon-delete2"></i></span>
					</span>
				</li>
			</ul>
			<el-upload class="avatar-uploader" :action="uploadUrl" :before-upload="beforeUpload" list-type="picture-card" :on-success="logoImgsPreview" :on-remove="logoImgsRemove">
				<i class="el-icon-plus"></i>
			</el-upload>
			<el-dialog v-model="licenceImgsVisible" size="tiny">
				<img width="100%" :src="licenceImgsUrl" alt="">
			</el-dialog>
			<span>提示:图片不超过1M，上传后显示缩略图</span>

		</el-form>
		<el-button type="info" style="width:100%;margin-top: 10px;" @click="shSave('formData')">保存</el-button>
	</el-card>
</template>

<script>
	import { customerSave, customerUpdate, customerInfo, upload, userList, metaList } from '@/api/getData'
	import { isPhoneVailable } from '@/config/mUtils'
	export default {
		data() {
			var validateMobile = (rule, value, callback) => {
				if(value === '') {
					callback(new Error('请输入手机号'));
				} else {
					if(isPhoneVailable(value)) {
						callback(new Error('请输入正确的手机号'));
					}
					callback();
				}
			};
			return {
				hasLicenceImg:false,
				hasloginImg:false,
				formData: {
					id: "",
					customerName: "",
					linkerPhone: "",
					linkerName: "",
					customerAddress: "",
					latitude: "",
					longitude: "",
					takePercent: "",
					areaId: "",
					bdId: "",
					bizId: "",
					runStatus: "1",
					licenceImgs: "",
					logoImgs: "",
				},
				userList: [],
				bdList: [],
				areaList: [],
				licenceImgsUrl: "",
				licenceImgsVisible: false,
				logoImgsVisible: false,
				etrName: "",
				names: [],
				local: null,
				map: null,
				uploadUrl: "",
				loginImg: [],
				licenceImg: [],
				rules:{
					customerName: [
			            { required: true, message: '请输入商户名称', trigger: 'blur' },
			            { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
			        ],
			        linkerName: [
			            { required: true, message: '请输入联系人名称', trigger: 'blur' },
			            { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
			        ],
			        customerAddress: [
			            { required: true, message: '请输入商户详细地址', trigger: 'blur' },
			            { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
			        ],
			        takePercent: [
			            { required: true, message: '请输入商户分成比例', trigger: 'blur' },
			            { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
			        ],
			        
			        linkerPhone: [{
						validator: validateMobile,
						trigger: 'blur'
					}],
				},
			}
		},
		mounted() {
			let _this = this;
			// 百度地图API功能
			_this.map = new BMap.Map("allmap"); // 创建地图实例
			_this.map.centerAndZoom(new BMap.Point(116.404, 39.915), 15);
			let options = {
				onSearchComplete: function(results) {
					// 判断状态是否正确
					//					if (local.getStatus() == BMAP_STATUS_SUCCESS){
					for(var i = 0; i < results.getCurrentNumPois(); i++) {
						_this.names.push(results.getPoi(i));
					}

					//					}
				}
			};
			_this.local = new BMap.LocalSearch(_this.map, options);

			this.uploadUrl = upload;
			this.metaList();
			this.userListFun();
			if(this.$route.query.id != undefined) {
				this.customerInfo(this.$route.query.id)
			}
		},
		methods: {
			haslicenceImgsRemove(url) {
				this.licenceImg.splice(this.licenceImg.indexOf(url), 1);
			},
			haslogoImgsRemove(url) {
				this.licenceImg.splice(this.licenceImg.indexOf(url), 1);
			},
			licenceImgsRemove(file, fileList) {
				this.licenceImg.splice(this.licenceImg.indexOf(file.response.data), 1);
			},
			licenceImgsPreview(res, file) {
				this.licenceImgsUrl = res.data;
				this.licenceImg.push(res.data);
				//this.licenceImgsVisible = true;
			},
			logoImgsRemove(file, fileList) {
				this.loginImg.splice(this.loginImg.indexOf(file.response.data), 1);
			},
			logoImgsPreview(res, file) {
				this.logoImgsUrl = res.data;
				this.loginImg.push(res.data);
				//this.logoImgsVisible = true;
			},
			beforeUpload(file) {
				const isJPG = file.type === 'image/jpeg';
				const isPNG = file.type === 'image/png';
				const isLt1M = file.size / 1024 / 1024 < 1;
				if(!isJPG && !isPNG) {
					this.$message.error('上传头像图片只能是 JPG和PNG 格式!');
				}
				if(!isLt1M) {
					this.$message.error('上传头像图片大小不能超过 1MB!');
				}
				return(isJPG || isPNG) && isLt1M;
			},
			changChild(id) {
				let _this = this;
				this.areaList.forEach(function(item) {
					if(item.id == id) {
						_this.bdList = item.childList;
						return false;
					}
				});
			},
			showOver: function(item) {
				console.log(item);
				this.formData.customerAddress = item.address;
				this.formData.latitude = item.point.lat;
				this.formData.longitude = item.point.lng;
				let point = new BMap.Point(item.point.lng, item.point.lat)
				this.map.centerAndZoom(point, 15);
				let marker = new BMap.Marker(new BMap.Point(item.point.lng, item.point.lat));
				this.map.addOverlay(marker);
				var opts = {
					width: 200, // 信息窗口宽度
					height: 100, // 信息窗口高度
					title: item.title, // 信息窗口标题
				}
				let infoWindow = new BMap.InfoWindow("地址：" + item.address, opts); // 创建信息窗口对象 
				this.map.openInfoWindow(infoWindow, point); //开启信息窗口
			},
			find: function() {

				this.local.search(this.etrName);
			},
			async userListFun() {
				try {
					const returnData = await userList({
						pageSize: "100",
						pageNum: "1",
						roleName: "BD负责人"
					});
					if(returnData.code == "0") {
						this.userList = returnData.list.rows;
					} else {
						this.$message({
							type: 'error',
							message: returnData.msg
						});
					}
				} catch(err) {
					console.log('获取数据失败', err);
				}
			},
			async customerInfo(shId) {
				try {
					const returnData = await customerInfo({
						"id": shId
					});
					if(returnData.code == "0") {
						this.formData.id = returnData.obj.id;
						this.formData.customerName = returnData.obj.customerName;
						this.formData.linkerPhone = returnData.obj.linkerPhone;
						this.formData.linkerName = returnData.obj.linkerName;
						this.formData.customerAddress = returnData.obj.customerAddress;
						this.formData.latitude = returnData.obj.latitude;
						this.formData.longitude = returnData.obj.longitude;
						this.formData.takePercent = returnData.obj.takePercent;
						this.formData.areaId = returnData.obj.areaId
						this.formData.bdId = returnData.obj.bdId;
						this.formData.bizId = returnData.obj.bizId;
						this.formData.runStatus = returnData.obj.runStatus;
						this.formData.licenceImgs = returnData.obj.licenceImgs;
						this.formData.logoImgs = returnData.obj.logoImgs;
						if(returnData.obj.licenceImgs != ""){
							this.licenceImg = returnData.obj.licenceImgs.split(",");
							this.hasLicenceImg = true;
						}
						if(returnData.obj.logoImgs != ""){
							this.loginImg = returnData.obj.logoImgs.split(",");
							this.hasloginImg = true;
						}
					} else {
						this.$message({
							type: 'error',
							message: returnData.msg
						});
					}
				} catch(err) {
					console.log('获取数据失败', err);
				}
			},
			async metaList() {
				const res = await metaList({
					type: "address",
					pageSize: "500",
					pageNum: "1",
				});
				if(res.code == "0") {
					let parentList = [];
					res.list.rows.forEach(function(item) {
						if(item.parentId == null || item.parentId == "") {
							item.childList = [];
							parentList.push(item);
						}
					});
					res.list.rows.forEach(function(item) {
						parentList.forEach(function(obj) {
							if(item.parentId == obj.id) {
								obj.childList.push(item);
							}
						});
					});
					this.areaList = parentList;
				} else {
					this.$notify.error({
						title: '错误',
						message: res.msg,
						offset: 100
					});
				}
			},
			async shSave(formData) {
				let _this = this;
				this.$refs[formData].validate(async(valid) => {
					if(valid) {

						try {
							if(_this.formData.latitude == "" || _this.formData.longitude == "" ){
								this.$notify.error({
									title: '提示',
									message: "请定位商户经纬度",
									offset: 100
								});
								return false;
							}
							if(_this.formData.areaId == ""){
								this.$notify.error({
									title: '提示',
									message: "请选择行政区",
									offset: 100
								});
								return false;
							}
							if(_this.formData.bdId == ""){
								this.$notify.error({
									title: '提示',
									message: "请选择BD负责人",
									offset: 100
								});
								return false;
							}							
							if(_this.formData.licenceImg.length  == 0){
								this.$notify.error({
									title: '提示',
									message: "请上传营业执照",
									offset: 100
								});
								return false;
							}
							if(_this.formData.loginImg.length  == 0){
								this.$notify.error({
									title: '提示',
									message: "请上传商户LOGO",
									offset: 100
								});
								return false;
							}
							let result = null;
							if(_this.licenceImg.length > 0) {
								_this.formData.licenceImgs = _this.licenceImg.join(",");
							}
							if(_this.loginImg.length > 0) {
								_this.formData.logoImgs = _this.loginImg.join(",");
							}
							if(_this.formData.id != "") {
								result = await customerUpdate(_this.formData);
							} else {
								result = await customerSave(_this.formData);
							}
							if(result.code == "0") {
								this.$message({
									type: 'success',
									message: '保存成功'
								});
								this.$router.push({
									path: 'shList'
								})
							}
						} catch(err) {
							console.log('获取数据失败', err);
						}
					} else {
						this.$notify.error({
							title: '错误',
							message: '请检查输入是否正确',
							offset: 100
						});
						return false;
					}
				});
			},
		},
	}
</script>

<style scoped>
	.box-card {
		margin: 0 10px;
	}
	
	.title {
		background-color: #20a0ff;
		line-height: 60px;
		font-size: 18px;
		color: #fff;
	}
	
	#allmap {
		height: 300px;
		width: 100%;
	}
	
	.resultMap {
		height: 265px;
		overflow: auto;

	}
	
	.itemMap {
		line-height: 30px;
		cursor: pointer;
		margin: 10px 0;
		padding-left: 10px;
	}
	
	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}
	
	.avatar-uploader .el-upload:hover {
		border-color: #20a0ff;
	}
	
	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		line-height: 178px;
		text-align: center;
	}
	
	.avatar {
		width: 178px;
		height: 178px;
		display: block;
	}
</style>